﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
//using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Server
{
    class SerialController :  IDisposable
    {

        string ReadingString;
        SerialData _data;
        public event SerialDataReceivedEventHandler PropertyChanged;
        //manufacturer specs for baud rate, databits, and stop bits
        static string portName = "COM10";
        static int baudRate = 115200;
        static int dataBits = 8;
        //instantialize a serial port object for arduino
        private SerialPort arduinoSerial = new SerialPort(portName, baudRate, Parity.None, dataBits, StopBits.One);

        //public SerialData Data
        //{
        //    get
        //    {
        //        return this._data;
        //    }

        //    set
        //    {
        //        if (value != this._data)
        //        {
        //            this._data = value;
        //            NotifyPropertyChanged();
        //        }
        //    }
        //}

        //constructor
        //public SerialController(Form ParentForm, Chart outputChart)
        public SerialController()
        {
            arduinoSerial.Handshake = Handshake.None;
            arduinoSerial.DtrEnable = true;
            arduinoSerial.DataReceived += new SerialDataReceivedEventHandler(mcu_DataReceived);
        }

        public void openPort()
        {
            if (!arduinoSerial.IsOpen)
            {
                arduinoSerial.Open();
            }

        }
        public void closePort()
        {
            arduinoSerial.Close();
        }

        public void Dispose() 
        {
            this.closePort();
        }
        // int RadiometerVoltageReadingInt;
        private void mcu_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //It's here that this.invoke()... cannot be called.

            ReadingString = (arduinoSerial.ReadLine().ToString());    //y-value
            // Debug.Print(RadiometerVoltageReadingString.ToString());

            convertFromJson(ReadingString);
        }


        private void convertFromJson(string ReadingString)
        {

           // this.Data = JsonConvert.DeserializeObject<SerialData>(ReadingString);
        }

        //private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        //{
        //    if (PropertyChanged != null)
        //    {
        //        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        //    }
        //}

    }
}
